package net.wangds.web.entrypoint;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 基本应答类.
 */
@ApiModel(value="普通应答", description = "返回体不是列表的应答.")
public class BaseResp<T> implements Resp{

    /**
     * 应答代码.
     *
     * 一般情况下“0”表示“正常”.
     */
    @ApiModelProperty(value = "执行结果, \"0\"表示正常，其他都是异常.", required = true)
    private int code;

    /**
     * 简单的字符串消息.
     *
     * 一般用于返回提示信息.
     */
    @ApiModelProperty(value = "执行结果未非\"0\"值时，保存错误提示.")
    private String msg;

    /**
     * 应答体.
     *
     * 应答的主体内容.
     */
    @ApiModelProperty(value = "返回业务体,不同接口返回体不同", required = true)
    private T body;

    /**
     * 跟踪信息.
     *
     * 请求处理的执行跟踪信息，一般在异常情况下会填写此字段.
     */
    @ApiModelProperty(value = "执行跟踪信息.")
    private String trace;

    /**
     * 服务版本.
     */
    @ApiModelProperty(value = "接口版本，暂时没有使用.")
    private int version;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }

    public String getTrace() {
        return trace;
    }

    public void setTrace(String trace) {
        this.trace = trace;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }


    public static <T> BaseResp<T> of(T body){
        BaseResp<T> res = new BaseResp<>();
        res.setBody(body);
        res.setCode(0);
        res.setMsg("success");
        res.setVersion(0);
        res.setTrace("");
        return res;
    }

    /**
     * 默认应答对象.
     * @param <T> body的类型.
     * @return 默认应答.
     * <p>默认应答对象返回值code为“-1”,body为“null”，msg为“未知错误”。</p>
     */
    public static <T> BaseResp<T> createDefault(){
        BaseResp<T> res = new BaseResp<>();
        res.setBody(null);
        res.setCode(-1);
        res.setMsg("未知错误");
        res.setVersion(0);
        res.setTrace("");
        return res;
    }

    public BaseResp<T> success(T body){
        return code(0).body(body).msg("success");
    }


    public BaseResp<T> failure(int code, String msg){
        return code(code).body(null).msg(msg);
    }


    public BaseResp<T> failure(int code){
        return code(code).body(null).msg("");
    }


    public BaseResp<T> code(int code){
        this.code = code;
        return this;
    }

    public BaseResp<T> msg(String msg){
        this.msg = msg;
        return this;
    }

    public BaseResp<T> version(int version){
        this.version = version;
        return this;
    }

    public BaseResp<T> trace(String trace){
        this.trace = trace;
        return this;
    }

    public BaseResp<T> body(T body){
        this.body = body;
        return this;
    }

}
